<template>
  <div>
    <div class="toolbar">
      <div>  <el-button style="float: right;margin: 0 0 10px 0" size="small" type="primary" @click="addBusin">新增角色</el-button></div>
      <analyse-table :table-data="tableData" :key_mapper="key_mapper" :sortable = "sort_mapper" :min-width = "180" size="small" @sort-change="sortChange">
        <el-table-column label="操作" min-width="170">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="edit(scope.row)" >编辑</el-button>
            <el-button type="danger" size="small" @click="deleterole(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </analyse-table>
      <el-pagination :current-page.sync="page" :page-size="size" :total.sync="total" class="mt-10" layout="total, sizes, prev, pager, next, jumper" @current-change="currentChange" @size-change="handleSizeChange"/>
      <el-dialog :visible.sync="dialogFormVisible" title="角色编辑">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="role_name" width>
            <el-input v-model="ruleForm.role_name" style="width: 80%" />
          </el-form-item>
          <el-form-item label="角色描述" prop="desc">
            <el-input v-model="ruleForm.desc" style="width: 80%" rows="5" type="textarea"/>
          </el-form-item>
          <el-form-item label="上级主管" prop="supervisor_id">
            <el-select v-model="ruleForm.supervisor_id" placeholder="请选择" >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
                sortable/>
            </el-select>
          </el-form-item>
          <el-form-item label="开放功能权限" prop="perm">
            <select-all :all-select-list="roleOptions" v-model="ruleForm.perm" />
          </el-form-item>
          <el-form-item label="表格展示字段" prop="">
            <el-select v-model="ruleForm.table" placeholder="请选择" @change="change" >
              <el-option
                v-for="item in optionsChoose"
                :key="item.value"
                :label="item.CName"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="取消展示项" prop="">
            <template v-for="(value, key) in permObj" >
              <el-checkbox-group v-if="key === ruleForm.table" v-model="permObj[key].exclude" :key="key" @change="judeLength">
                <el-checkbox v-for="cell in value.list" :label="cell.key" :key="cell.value">{{ cell.name }}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" size="small" @click="send">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRolePreset, getRoleList, creatRole, editRole, tablePreset,deleterole } from '@/api/role'
import { pickTime } from '@/model/DateRange'
import SelectAll from '@/components/SelectAll'
import mixins from '@/model/mixins'
import mixinsEidt from '@/model/mixinsEidt'
import {useVcode} from '@/utils/Vcode'

const exArr = ['cp_lottery', 'recharge', 'withdraw', 'recharge_detail', 'withdraw_detail', 'platform_reward_detail', 'tax']

export default {
  name: 'Help',
  components: {
    SelectAll
  },
  mixins: [mixins, mixinsEidt],
  data() {
    return {
      dialogFormVisible: false,
      form: {},
      queryFrom: {
        merchant: '',
        time_range: pickTime
      },
      id: '',
      options: [],
      roleOptions: [],
      sort_mapper:['id', 'role_name','desc',"permTrans"],
      key_mapper: [
        { key: 'id', name: '角色ID', width: 70 },
        { key: 'role_name', name: '角色名称', width: 145 }, { key: 'desc', name: '角色描述', width: 145 },
        { key: 'supervisor_name', name: '上级主管', width: 145 }, { key: 'permTrans', name: '开放功能权限', width: 145 },
        { key: 'updated_at', name: '最后修改时间', width: 145 },
        { key: 'created_at', name: '创建时间', width: 145 }
      ],
      ruleForm: {
        perm: []
      },
      rules: {
        role_name: [{ required: true, min: 1, max: 30, message: '请填写角色名称', trigger: 'blur' }],
        desc: [{ required: true, min: 1, message: '请填写角色描述', trigger: 'blur' }],
        supervisor_id: [{ required: true, message: '请选择上级主管', trigger: 'blur' }],
        perm: [{ required: true, message: '请选择开放权限功能', trigger: 'blur' }]
      },
      trans: {},
      creatAPI: creatRole,
      editAPT: editRole,
      key: '',
      cellList: [],
      checkedCities: {},
      excludeObj: {},
      permObj: {}
    }
  },
  computed: {
    optionsChoose() {
      // console.log(this.roleOptions.filter(item => this.ruleForm.perm.includes(item.value)))
      return this.roleOptions.filter(item => this.ruleForm.perm.includes(item.value))
    }
  },
  watch: {
    async optionsChoose() {
      for (const item of this.optionsChoose) {
        if (!this.permObj[item.value]) {
          this.permObj[item.value] = {
            list: exArr.includes(item.value) ? [] : await this.showDetail(item.value),
            exclude: this.excludeObj[item.value] || []
          }
          // console.log(this.permObj[item.value])
        }
      }
      // console.log(this.permObj)
      // console.log(this.checkedCities)
    }
  },
  created() {
    this.update()
  },
  methods: {

    deleterole(row) {
      this.$confirm(`确认删除ID为${row.id}的角色: ${row.role_name}？`, '是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        useVcode(this, () => {
          deleterole(row.id, {}).then(() => {
            this.$message({ type: 'success', message: '删除成功!' })
            this.clear()
              this.update()
          }, err => {
            this.$message({ type: 'error', message: err.response.data.msg })
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async update(data = { page: this.page, size: this.size }) {
      await getRolePreset({}).then(res => {
        this.roleOptions = res.data.perm_list.map(item => {
          this.trans[item.key] = item.value
          return { name: '全选/取消', CName: item.value, value: item.key }
        })
        this.options = res.data.supervisor_list.map(item => {
          return { label: item.value, value: item.key }
        })
      })
      await this.getData(data)
    },
    getData(data) {
      getRoleList(data).then(res => {
        // this.sendDate = JSON.parse(JSON.stringify(data))
        // this.total_count = res.data.total_count || 1
        this.tableData = res.data.list.map(item => {
          let data = item
         let permTrans_ = item.perm.map(item2 => {
            return this.trans[item2.key]
          })
         let permTrans=permTrans_&&permTrans_[0]+'【'+permTrans_.length+'】'
          data=Object.assign(data,{permTrans});
          this.$forceUpdate()
          return data
        })
      }, err => {
        this.$message({ type: 'error', message: err.response.data.msg })
      })
    },
    change(value) {
      this.permObj = JSON.parse(JSON.stringify(this.permObj))
      this.permObj[value].exclude = [...new Set(this.permObj[value].exclude)]
      // this.cellList = this.permObj[value].exclude
      // console.log(this.cellList)
    },
    judeLength(value, length) {
    },
    showDetail(page_id) {
      return tablePreset({ page_id: page_id }).then(res => {
        return res.data
      })
    },
    edit(row) {
      this.id = row.id
      this.ruleForm = {
        role_name: row.role_name,
        desc: row.desc,
        supervisor_id: row.supervisor_id,
        perm: row.perm.map(item => item.key)
      }
      this.excludeObj = {}
      row.perm.forEach(item => {
        this.excludeObj[item.key] = item.exclude_name
      })
      this.permObj = {}
      this.options = this.options.map(item => {
        const data = item
        if (item.value === row.id) {
          data.disabled = true
          return data
        } else {
          data.disabled = false
          return data
        }
      })
      this.dialogFormVisible = true
    },
    clear() {
      this.ruleForm = {
        role_name: '',
        desc: '',
        supervisor_id: '',
        perm: []
      }
      this.permObj = {}
    },
    send() {
      useVcode(this, () => {
      this.$refs['ruleForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.id) {
          const permObj = {}
          for (const item in this.permObj) {
            permObj[item] = this.permObj[item].exclude
          }
          const data = Object.assign({}, this.ruleForm, { perm: permObj })
          delete data.table
          console.log(data)
          editRole(data, this.id).then(() => {
            this.$message({ message: '保存成功', type: 'success' })
            this.dialogFormVisible = false
            this.clear()
            this.update(this.sendDate)
          }, err => {
            this.$message({ type: 'error', message: err.response.data.msg })
          })
        } else {
          const permObj = {}
          for (const item in this.permObj) {
            permObj[item] = this.permObj[item].exclude
          }
          const data = Object.assign({}, this.ruleForm, { perm: permObj })
          delete data.table
          creatRole(data).then(() => {
            this.$message({ message: '保存成功', type: 'success' })
            this.dialogFormVisible = false
            this.clear()
            this.update(this.sendDate)
          }, err => {
            this.$message({ type: 'error', message: err.response.data.msg })
          })
        }
      })
      })
    }
  }
}
</script>
